package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.common.OrderDetail;
import com.cskaoyan.mapper.*;
import com.cskaoyan.util.AuthenticationUtil;
import com.cskaoyan.util.MyBatisUtil;
import com.cskaoyan.util.StringUtil;
import com.cskaoyan.util.TransactionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderServiceImpl implements OrderService {

    static String ip="127.0.0.1";

    @Override
    public BaseRespVo list(String ips,Integer page, Integer limit, String sort, String order,
                           String userId, String orderSn, Date start, Date end,List<Short> orderStatusArray) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketOrderMapper mapper = sqlSession.getMapper(MarketOrderMapper.class);

        ip=ips;

        PageHelper.startPage(page,limit);

        MarketOrderExample example = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = example.createCriteria();
        if (userId!=null&&userId!=""){
            criteria.andUserIdEqualTo(Integer.parseInt(userId));
        }
        if (orderSn!=null&&orderSn!=""){
            criteria.andOrderSnEqualTo(orderSn);
        }
        if (!StringUtil.isEmpty(orderSn)) {
            criteria.andOrderSnEqualTo(orderSn);
        }
        if (start != null && end != null) {
            criteria.andAddTimeGreaterThanOrEqualTo(start).andAddTimeLessThanOrEqualTo(end);
        }
        if (orderStatusArray != null && orderStatusArray.size() != 0) {
            criteria.andOrderStatusIn(orderStatusArray);
        }
        criteria.andDeletedEqualTo(false);
        example.setOrderByClause(sort + " " + order);
        List<MarketOrder> marketOrders = mapper.selectByExample(example);


        PageInfo pageInfo = new PageInfo(marketOrders);
        sqlSession.close();// 不要忘记
        return BaseRespVo.ok(CommonData.data(pageInfo));
    }

    @Override
    public BaseRespVo detail(Integer id) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketOrderMapper mapper = sqlSession.getMapper(MarketOrderMapper.class);
        MarketOrder marketOrder = mapper.selectByPrimaryKey(id);
        Integer userId = marketOrder.getUserId();

        OrderGoodsService orderGoodsService = new OrderGoodsServiceImpl();
        List<MarketOrderGoods> marketOrderGoods = orderGoodsService.selectByExample(marketOrder.getId());
        UserService userService = new UserServiceImpl();
        MarketUser marketUser = userService.selectByPrimaryKey(userId);
        OrderDetail orderDetail = new OrderDetail(marketOrder, marketOrderGoods, marketUser);



        sqlSession.close();// 不要忘记
        System.out.println(BaseRespVo.ok(orderDetail));
        return BaseRespVo.ok(orderDetail);
    }

    @Override
    public BaseRespVo ship(Integer orderId, String shipChannel, String shipSn) {
        //对数据库的处理
        //对订单进行发货处理
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketOrderMapper mapper = sqlSession.getMapper(MarketOrderMapper.class);
        MarketOrder marketOrder = mapper.selectByPrimaryKey(orderId);
//        System.out.println(marketOrder);

        marketOrder.setOrderStatus((short)301);
        marketOrder.setShipSn(shipSn);
        marketOrder.setShipChannel(shipChannel);
        mapper.updateByPrimaryKey(marketOrder);


        //日志修改

        insertLog(sqlSession, "发货");


        sqlSession.commit();
        sqlSession.close();
        //返回一个消息
        return BaseRespVo.ok();
    }

    @Override
    public BaseRespVo delete(Integer orderId) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketOrderMapper mapper = sqlSession.getMapper(MarketOrderMapper.class);
        int i = mapper.deleteByPrimaryKey(orderId);
        OrderGoodsService orderGoodsService = new OrderGoodsServiceImpl();
        orderGoodsService.deleteByOrderId(orderId,sqlSession);

        insertLog(sqlSession,"删除订单");

        sqlSession.commit();
        sqlSession.close();
        return BaseRespVo.ok();
    }

    @Override
    public BaseRespVo refund(Map map,String ip) {
        Integer orderId = (Integer)map.get("orderId");
        int refundMoney = (int)map.get("refundMoney");
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        //状态修改
        MarketOrderMapper mapper1 = sqlSession.getMapper(MarketOrderMapper.class);
        MarketOrder marketOrder = mapper1.selectByPrimaryKey(orderId);
        marketOrder.setOrderStatus((short)203);
        marketOrder.setRefundTime(new Date());
        marketOrder.setRefundAmount(marketOrder.getActualPrice());
        marketOrder.setRefundType("支付宝！！！！");
        mapper1.updateByPrimaryKey(marketOrder);

        //优惠群券返还
        //更新 优惠券的状态
        MarketCouponUserMapper mapper = sqlSession.getMapper(MarketCouponUserMapper.class);
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketCouponUser> marketCouponUsers = mapper.selectByExample(marketCouponUserExample);
        //没有优惠券
        if (marketCouponUsers.size()!=0){
            MarketCouponUser marketCouponUser = marketCouponUsers.get(0);
            Integer couponId = marketCouponUser.getCouponId();
            marketCouponUser.setStatus((short)0);
            mapper.updateByPrimaryKey(marketCouponUser);
            //更新优惠券的总数
            MarketCouponMapper marketCouponMapperMapper = sqlSession.getMapper(MarketCouponMapper.class);

            MarketCoupon marketCoupon = marketCouponMapperMapper.selectByPrimaryKey(couponId);
            marketCoupon.setTotal(marketCoupon.getTotal() + 1);
            marketCouponMapperMapper.updateByPrimaryKey(marketCoupon);
        }

        //库存修改
        MarketOrderGoodsMapper marketOrderGoodsMapper = sqlSession.getMapper(MarketOrderGoodsMapper.class);
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);

        MarketGoodsProductMapper marketGoodsProductMapper = sqlSession.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsProductExample marketGoodsProductExample ;



        List<MarketGoodsProduct> marketGoodsProducts ;
        //i订单的商品种类不一定只有一个
        if (marketOrderGoods.size()>0){
            for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
                //工具doodsI查找
                marketGoodsProductExample=new MarketGoodsProductExample();
                MarketGoodsProductExample.Criteria marketGoodsProductExampleCriteria = marketGoodsProductExample.createCriteria();
                marketGoodsProductExampleCriteria.andGoodsIdEqualTo(marketOrderGood.getGoodsId());
                marketGoodsProducts = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
                if (marketGoodsProducts.size()<0)
                    continue;
                MarketGoodsProduct marketGoodsProduct = marketGoodsProducts.get(0);


                //更新数量
                marketGoodsProduct.setNumber(marketGoodsProduct.getNumber()+marketOrderGood.getNumber());
                marketGoodsProductMapper.updateByPrimaryKey(marketGoodsProduct);

            }
        }


        //日志修改

        insertLog(sqlSession, "退款");


        sqlSession.commit();
        return BaseRespVo.ok();
    }

    private void insertLog(SqlSession sqlSession, String operation) {
        MarketAdmin marketAdmin = (MarketAdmin) AuthenticationUtil.getPrincipal();
        String username = marketAdmin.getUsername();
        MarketLogMapper marketLogMapper = sqlSession.getMapper(MarketLogMapper.class);
        MarketLog marketLog = new MarketLog();

        marketLog.setAdmin(username);
        marketLog.setAction(operation);
        marketLog.setAddTime(new Date());
        marketLog.setUpdateTime(new Date());

        marketLog.setIp(ip);
        marketLog.setType(2);

        marketLogMapper.insert(marketLog);
    }
}

